package com.ruoyi.project.ins.queue;

import com.ruoyi.project.ins.domain.InsRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
@Component
public class RegisterQueueManager {
    // 阻塞队列（线程安全）
    private final BlockingQueue<InsRegister> queue = new LinkedBlockingQueue<>(1000);

    private final int threadCount = Runtime.getRuntime().availableProcessors();

    private final ExecutorService executor = new ThreadPoolExecutor(
            threadCount,               // corePoolSize
            threadCount,               // maximumPoolSize
            60, TimeUnit.SECONDS,      // keepAliveTime
            new LinkedBlockingQueue<>(1000), // 工作队列（防止内存撑爆）
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
    );

    @PostConstruct
    public void startConsumer() {
        // 启动多个线程消费队列
        for (int i = 0; i < threadCount; i++) {
            executor.submit(() -> {
                while (true) {
                    try {
                        InsRegister data = queue.take(); // 阻塞等待数据
                        handleRegistration(data);         // 执行注册逻辑
                    } catch (Exception e) {
                        log.error("处理注册失败信息：", e);
                    }
                }
            });
        }
    }


    public boolean tryAddBatch(List<InsRegister> dataList) {
        int remaining = queue.remainingCapacity();
        if (remaining >= dataList.size()) {
            for (InsRegister data : dataList) {
                queue.offer(data); // 入队
            }
            log.info("批量添加注册信息成功");
            return true;
        } else {
            log.error("队列容量不足，当前剩余: {}，请求: {}", remaining, dataList.size());
            return false;
        }
    }

    public boolean addToQueue(InsRegister data) {
        boolean success = queue.offer(data);
        if (!success) {
            log.error("队列已满，任务丢弃：{}", data.getEmailAccount());
            return false;
        }
        log.info("队列任务添加成功: {}", data.getEmailAccount());
        return true;
    }

    private void handleRegistration(InsRegister data) {
        // 模拟调用外部接口
        log.info("正在处理注册数据: {}", data.getEmailAccount());
        // 实际可以用RestTemplate / WebClient / Feign去调用其他服务
        log.info("注册成功: {}", data.getEmailAccount());
    }
}
